package com.zipking.cloud.springbootmybatis.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zipking.cloud.springbootmybatis.persistance.entity.ProductStock;
import com.zipking.cloud.springbootmybatis.persistance.mapper.ProductStockMapper;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/redis")
public class RedisController {
    @Autowired
     private ProductStockMapper productStockMapper;

    @Autowired
    private  RedisTemplate   redisTemplate;
    //延迟双删：
    @PostMapping(value = "/ysDelete")
    public String ysDelete(Long productId,Long productCnt) throws Exception {
// 1. 更新MySQL
//        mysql.update("UPDATE books SET title = ? WHERE id = ?",
//                book.getTitle(), book.getId());

        LambdaUpdateWrapper<ProductStock> productStockLambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        productStockLambdaUpdateWrapper.eq(ProductStock::getProductId,productId);
        ProductStock productStock=new ProductStock();
        productStock.setProductCnt(productCnt);
        this.productStockMapper.update(productStock,productStockLambdaUpdateWrapper);
        // 2. 删除缓存
        redisTemplate.delete("products:" + productId);

        // 3. 延迟一段时间后再次删除缓存
        Thread.sleep(500);  // 或使用定时任务
        redisTemplate.delete("products:" + productId);
        return "ok";
    }

    @GetMapping(value = "/getProduct")
    public Object getProduct(Long productId) throws Exception {

       // redisTemplate.opsForValue().get("products:" + productStock.getProductId())
        ProductStock productStock = this.productStockMapper.selectById(productId);
        redisTemplate.opsForValue().set("products:" + productStock.getProductId(),productStock.getProductId());
        return productStock;
    }
}
